package com.ruoyi.ruoyiqywechat.openfeignconfig;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
@Slf4j
public class ServiceDiscoveryUtil {

    @Autowired
    private DiscoveryClient discoveryClient;

    // 检查所有可用服务
    @PostConstruct
    public void checkAllServices() {
        log.info("=== Nacos服务发现验证 ===");

        // 获取所有服务名称
        List<String> services = discoveryClient.getServices();
        log.info("总服务数量: {}", services.size());

        for (String service : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            log.info("服务: {}, 实例数: {}", service, instances.size());

            for (ServiceInstance instance : instances) {
                log.info("  - 实例: {}:{}", instance.getHost(), instance.getPort());
                log.info("  - URI: {}", instance.getUri());
            }
        }
    }

    // 检查特定服务
    public boolean isServiceAvailable(String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        return instances != null && !instances.isEmpty();
    }
}
